package com.gerald.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.gerald.shop.entity.GoodsEntity;
import com.gerald.shop.service.IGoodsSearchService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Map;

/**
 * @author Gerald 2022/1/6 19:38
 * description:
 */
@Service
public class GoodsSearchServiceImpl implements IGoodsSearchService {

    @Value("${es.index}")
    private String index;

    @Value("${es.type}")
    private String type;

    /**
     *@author Gerald 2022/1/6 19:56
     *description:操作es
     * java访问es客户端
     */
    @Autowired
    private RestHighLevelClient client;



    @Override
    public void add(GoodsEntity goodsEntity) throws Exception {
        //1. 准备request对象 创建索引类型，没有会自动创建
        IndexRequest request = new IndexRequest();
        request.index(index).type(type);
        //转换格式
        request.source(JSON.toJSONString(goodsEntity), XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

    }

    @Override
    public List<GoodsEntity> search(Map<String, Object> param) throws Exception{
        return null;
    }

    @Override
    public void deleteId(Integer id) throws Exception{

    }

    /**
     *@author Gerald 2022/1/6 21:13
     *description:删除es中创建的新索引
     */
    @Override
    public void clean() throws Exception {

        DeleteByQueryRequest request = new DeleteByQueryRequest();
        request.indices(index);
        request.types(type);
        request.setQuery(QueryBuilders.matchAllQuery());
        BulkByScrollResponse bulkByScrollResponse = client.deleteByQuery(request, RequestOptions.DEFAULT);
    }
}
